﻿
Dcqtech_Form_Controls.WordList = $.extend({}, Dcqtech_Form_Controls.Default);

Dcqtech_Form_Controls.WordList.setValue = function (id, value, fieldInfo, $root, isFirstSet) {
    $root.find("[dcqtech_data='" + id + "']").val(value);
    dcq_word_init(id, value);
};

Dcqtech_Form_Controls.WordList.setDefaultValue = function (id, $root, fieldInfo) {
    var value = fieldInfo.defaultValue;
    if (!value) return;
    Dcqtech_Form_Controls.WordList.setValue(id, value, fieldInfo, $root);
};

Dcqtech_Form_Controls.WordList.setReadonly = function (id, isReadOnly) {
    if (typeof isReadOnly != "boolean") {
        isReadOnly = isReadOnly == "1";
    }
    if (isReadOnly) {
        $("[dcqtech_id='" + id + "'] .fileinput-button").hide();
    }
};

Dcqtech_Form_Controls.WordList.setEditEvent = function (id, wdInfo, $root) {
    //var $control = $root.find("[dcqtech_id='" + id + "'] ");
    $root.find("[dcqtech_id='" + id + "'] input[type=file]").fileupload({
        url: Dcqtech.Url.Content("~/WorkFlowRuntime/Attachment/upload"),
        dataType: 'json',
        add: function (e, data) {
            parent.waitingDialog.show("附件上传中...");
            data.submit();
        },
        done: function (e, data) {
            var id = $(e.target).parents("[dcqtech_id]").attr("dcqtech_id");
            var infos = DcqtechWordFileInfos[id];
            if (!infos || infos.length === 0) {
                infos = [];
            }
            infos.push(data.result.Data.success[0]);
            DcqtechWordFileInfos[id] = infos;
            showDcqtechWordFileHtme(id);
            parent.waitingDialog.hide();
        }
    });
    showDcqtechWordFileHtme(id);
};

Dcqtech_Form_Controls.WordList.setViewEvent = function (id, fieldInfo, $root) {
    var $control = $root.find("[dcqtech_id='" + id + "']");
    $control.find(".fileinput-button").hide();
}


function ToHumanSize(size) {
    if (size > 1024 * 1024 * 1024) {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + "G";
    }
    else if (size > 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + "M";
    }
    else if (size > 1024) {
        return (size / (1024)).toFixed(2) + "K";
    }
    else {
        return size + "B";
    }
}

var DcqtechWordFileInfos = DcqtechWordFileInfos || {};

function showDcqtechWordFileHtme(id) {
    var infos = DcqtechWordFileInfos[id];
    var isReadonly = Dcqtech_Form.formInfos.fieldInfos[id].isReadOnly == "1";
    if (!infos || (infos.length === 0)) {
        $("[dcqtech_id='" + id + "'] ul.list-group").html("<li>请先上传文档！</li>");
        $("[dcqtech_data='" + id + "']").val("");
    } else {
        var html = [];
        var fileids = [];
        for (var i = 0; i < infos.length; i++) {
            var fileInfo = infos[i];
            html.push('<li class="clearfix  list-group-item" index="', i, '" id="', fileInfo.GUID, '"><i class="fa fa-2x fa-file-word-o blue"></i> <span role="filename" class="bigger-130">', fileInfo.FILENAME, '</span>');
            html.push('  <span class="label label-primary" > ', fileInfo.SIZE, '</span>');
            html.push('<span class="pull-right" >');
            if (Dcqtech_Form.isEdit && !isReadonly) html.push(' <button class="btn btn-info btn-xs" role="edit" onclick="dcq_word_edit(this);"> <i class="fa fa-edit" > </i> 编辑</button> ');

            html.push(' <button class="btn btn-info btn-xs" role="view" onclick="dcq_word_view(this);" > <i class="fa fa-eye" > </i> 查看</button> ');
            html.push(' <a class="btn btn-info btn-xs" role="download" target="_blank" href="', Dcqtech.Url.BaseUrl, 'WorkFlowRuntime/Attachment/download?id=', fileInfo.GUID, '" > <i class="fa fa-download" > </i> 下载</a> ');
            if (Dcqtech_Form.isEdit && !isReadonly) html.push(' <button class="btn btn-danger btn-xs" role="delete" onclick="dcq_word_delete(this);" > <i class="fa fa-remove" > </i> 删除</button> ');
            html.push('</span>');
            html.push('</li>');
            fileids.push(fileInfo.GUID);
        }
        $("[dcqtech_id='" + id + "'] ul.list-group").html(html.join(''));
        $("[dcqtech_data='" + id + "']").val(fileids.join(','));
    }
}

var dcqtech_current_edit_wordinfo = {};

function dcq_word_edit(obj) {
    var $this = $(obj);
    var index = parseInt($this.parents("li.list-group-item").attr("index"), 10);
    var id = $this.parents("[dcqtech_id]").attr("dcqtech_id");
    var fileInfos = DcqtechWordFileInfos[id];
    var wordId = fileInfos[index].GUID;
    var filename = fileInfos[index].FILENAME;
    dcqtech_current_edit_wordinfo = {
        index: index,
        id: id
    }
    console.info(wordId, filename);
    parent.waitingDialog.show("Word文件编辑中，请不要关闭此窗口！");
    word_sendCmd({
        cmd: "edit",
        wordId: wordId,
        filename: filename,
        username: localStorage.getItem('dcqtech_login_username'),
        audit: true
    });
}

function dcq_word_view(obj) {
    var li = $(obj).parents("li.list-group-item")[0];
    var wordId = li.id;
    var filename = $(li).find("span[role='filename']").text();
    console.info(wordId, filename);
    word_sendCmd({
        cmd: "view",
        wordId: wordId,
        filename: filename,
        audit: false
    });
}
var websocket_WordList;
function word_sendCmd(cmd) {
    websocket_WordList = new WebSocket("ws://localhost:7701/Word");
    websocket_WordList.onopen = function () {
        websocket_WordList.send(JSON.stringify(cmd));
    }
    websocket_WordList.onmessage = function (e) {
        var cmd = JSON.parse(e.data);
        if (cmd.cmd == "msg") {
            parent.toastr.info(cmd.msg);
            return;
        }
        if (cmd.cmd == "editok") {
            parent.waitingDialog.hide();
            if (cmd.isChanged) {
                //cmd.worldInfo
                DcqtechWordFileInfos[dcqtech_current_edit_wordinfo.id][dcqtech_current_edit_wordinfo.index] = cmd.wordInfo;
                showDcqtechWordFileHtme(dcqtech_current_edit_wordinfo.id);
            } else {
                parent.eModal.alert("文件未修改！");
            }
        }
    };
    websocket_WordList.onerror = function () {
        parent.waitingDialog.hide();
        parent.eModal.alert("桌面助手打开失败，<a href='" + Dcqtech.Url.Content("~/static/officehelper/index.html") + "' target='_black'>点击进入下载页面</a>", "提示");
    }
    //websocket_WordList
    var wsCmd = new WsCmd("ws://localhost:7701/Word", function () {
        wsCmd.sendCmd(cmd);
    }, function () {
        parent.waitingDialog.hide();
        parent.eModal.alert("桌面助手打开失败，<a href='" + Dcqtech.Url.Content("~/static/officehelper/index.html") + "' target='_black'>点击进入下载页面</a>", "提示");
        //alert("桌面助手打开失败，转到下载页面！");
    });
    //websocketInfo.defaultCmdResult = function (cmd) {
    //    if (cmd.cmd == "msg") {
    //        parent.toastr.info(cmd.msg);
    //        return;
    //    }
    //    if (cmd.cmd == "editok") {
    //        parent.waitingDialog.hide();
    //        if (cmd.isChanged) {
    //            //cmd.worldInfo
    //            DcqtechWordFileInfos[dcqtech_current_edit_wordinfo.id][dcqtech_current_edit_wordinfo.index] = cmd.wordInfo;
    //            showDcqtechWordFileHtme(dcqtech_current_edit_wordinfo.id);
    //        } else {
    //            parent.eModal.alert("文件未修改！");
    //        }
    //    }
    //    console.info(cmd);
    //};
    //wsCmd.open();
}

function dcq_word_delete(obj) {
    var $this = $(obj);
    var index = parseInt($this.parents("li.list-group-item").attr("index"), 10);
    var id = $this.parents("[dcqtech_id]").attr("dcqtech_id");
    var fileInfos = DcqtechWordFileInfos[id];
    var wordId = fileInfos[index].GUID;
    var filename = fileInfos[index].FILENAME;
    if (confirm("确定要删除文档：“" + filename + "”吗?")) {
        DcqtechWordFileInfos[id].splice(index, 1);
        showDcqtechWordFileHtme(id);
    }
}




function dcq_word_init(id, ids) {

    if (ids) {
        Dcqtech.getJSON("~/WorkFlowRuntime/Attachment/GetByIds?ids=" + ids, function (ret) {
            if (ret && ret.length) {
                for (var i = 0; i < ret.length; i++) {
                    ret[i].SIZE = ToHumanSize(ret[i].SIZE);
                }
            }
            DcqtechWordFileInfos[id] = ret;
            showDcqtechWordFileHtme(id);
            console.info(ret);
        });
    } else {
        showDcqtechWordFileHtme(id);
    }



}
